package com.example.test_mqtt2

import android.content.Context
import android.util.Log
import org.eclipse.paho.android.service.MqttAndroidClient
import org.eclipse.paho.client.mqttv3.IMqttActionListener
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken
import org.eclipse.paho.client.mqttv3.IMqttToken
import org.eclipse.paho.client.mqttv3.MqttCallback
import org.eclipse.paho.client.mqttv3.MqttConnectOptions
import org.eclipse.paho.client.mqttv3.MqttMessage

/**
 * @author ytx
 * @date 2025-10-09 14:09
 * @description
 */
class MqttManager(
    private val context: Context, //上下文
    private val serverUri: String,//mqtt服务器地址
    private val clientId: String = "android_client_${System.currentTimeMillis()}" //客户端id
) {
    private var mqttClient: MqttAndroidClient? = null //mqtt客户端
    companion object{
        private const val TAG = "MqttManager"
    }

    // 连接配置
    private val mqttOptions = MqttConnectOptions().apply {
//        userName = "admin"       // 用户名（可选）
//        password = "password".toCharArray()  // 密码（可选）
        isCleanSession = true    // 是否清除会话
        connectionTimeout = 10   // 连接超时（秒）
        keepAliveInterval = 20   // 心跳间隔（秒）
        isAutomaticReconnect = true // 自动重连
        // 设置遗嘱消息（客户端异常断开时发送）
//        setWill("status/$clientId", "offline".toByteArray(), 1, true)
    }

    fun connect(){
        mqttClient = MqttAndroidClient(context,serverUri,clientId)
        mqttClient?.setCallback(object : MqttCallback {
            override fun connectionLost(p0: Throwable?) {
                Log.d(TAG, "断开链接:${p0?.message} ")
            }

            override fun messageArrived(p0: String?, p1: MqttMessage?) {
                Log.d(TAG, "收到消息: topic:$p0 ${p1?.payload?.decodeToString()}")
            }

            override fun deliveryComplete(p0: IMqttDeliveryToken?) {
                Log.d(TAG, "消息发送完毕: ")
            }
        })
        mqttClient?.connect(mqttOptions,null,object : IMqttActionListener{
            override fun onSuccess(p0: IMqttToken?) {
                Log.d(TAG, "链接成功: ")
                subscribe("test/android")
            }

            override fun onFailure(p0: IMqttToken?, p1: Throwable?) {
                Log.d(TAG, "链接失败")
            }

        })

    }

    /**
     * 订阅
     */

    fun subscribe(topic:String){
        mqttClient?.subscribe(topic,1,null,object : IMqttActionListener{
            override fun onSuccess(p0: IMqttToken?) {
                Log.d(TAG, "订阅成功: ")
            }

            override fun onFailure(p0: IMqttToken?, p1: Throwable?) {
                Log.d(TAG, "订阅失败: ")
            }
        })

    }

    /**
     * 发布
     */

    fun publish(topic:String,message:String){
        mqttClient?.publish(topic,message.toByteArray(),1,true)
        Log.d(TAG, "发送消息成功$message: ")
    }

    /**
     * 断开链接
     */
    fun disconnect(){
        mqttClient?.disconnect(null,object : IMqttActionListener{
            override fun onSuccess(p0: IMqttToken?) {
                Log.d(TAG, "断开成功: ")
            }

            override fun onFailure(p0: IMqttToken?, p1: Throwable?) {
                Log.d(TAG, "断开失败")
            }
        })

    }
}